package main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;

import utils.Pair;

public class Decoder {

	
	public static Solution getSolution(String satFilePath, LiteralAlocatorAndMap map) {
		Solution solution = null;
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(satFilePath)));
			String lastLine = "";
			String line;
			while ((line = br.readLine()) != null){
				if (line.equalsIgnoreCase("UNSAT") || line.equalsIgnoreCase("DONE")){
					break;
				}else{
					lastLine = line;
				}
			}
			
			String[] tokens = lastLine.split(" ");
			
			HashMap<Integer, Boolean> litsToVal = new HashMap<>();
			for (String litString : tokens) {
				int lit = Integer.parseInt(litString);
				litsToVal.put(Math.abs(lit), lit>0?true:false);
			}
			HashMap<Integer, Boolean> nodes = new HashMap<>(); 
			for (int i = 1; i <= map.getNumOfVertices(); i++){
				int lit = map.getStrongNodeLit(i);
				boolean val = litsToVal.get(lit);
				nodes.put(i, val);
			}
			
			int[] sumBits = map.getSumBits();
			for (int i = 0; i < sumBits.length; i++) {
				if (!litsToVal.get(sumBits[i])){
					sumBits[i] = -sumBits[i];
				}
			}
			
			int numOfStrong = binaryToDecimal(sumBits);
			
			
			solution = new Solution(nodes, numOfStrong);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return solution;
	}
	
	public static int binaryToDecimal(int[] sumBits){
		int numOfEdges = 0;
		
		for (int i = 0; i<sumBits.length; i++){
			int bit = -1;
			int lit = sumBits[i];
			if (lit>0)
				bit = 1;
			else
				bit = 0;
			numOfEdges += bit*Math.pow(2, i);
		}
		return numOfEdges;
	}	
}